package com.lagou.study.service.impl;

import com.lagou.study.mapper.CodeMapper;
import com.lagou.study.pojo.LagouAuthCode;
import com.lagou.study.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    CodeMapper codeMapper;

    @Override
    public LagouAuthCode saveCode(String email, String code) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        lagouAuthCode.setCode(code);
        Date now = new Date();
        Date after = new Date(now.getTime() + 600000);
        lagouAuthCode.setCreatetime(now);
        lagouAuthCode.setExpiretime(after);
        LagouAuthCode newLagouAuthCode = codeMapper.saveAndFlush(lagouAuthCode);
        return newLagouAuthCode;
    }

    @Override
    public Integer validateCodeByEmail(String email, String code) {
        LagouAuthCode lagouAuthCode = codeMapper.selectCodeByEmail(email);
        // 没有发送过验证码，没验证码可取
        if(lagouAuthCode == null){
            return 3;
        } else {
            String savedCode = lagouAuthCode.getCode();
            Date now = new Date();
            // 验证码超时
            if(now.compareTo(lagouAuthCode.getExpiretime())==1){
                return 2;
            } else {
                // 验证码匹配，正确
                if (savedCode.equals(code)){
                    return 0;
                } else {
                    // 验证码不匹配，错误
                    return 1;
                }
            }
        }
    }
}
